package com.iris.jvmtest.thread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @date : 2017年10月25日 上午11:22:05
 * @author : Iris.Xiao
 * @version : 1.0
 * @description :
 */
public class VolatileTest2 {
//	public static volatile int race = 0;
	public static volatile AtomicInteger race = new AtomicInteger(0);//原子数保证并发

	public static void increase() {
		race.incrementAndGet();
	}

	private static final int THREADS_COUNT = 50;

	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		Thread[] threads = new Thread[THREADS_COUNT];
		for (int i = 0; i < THREADS_COUNT; i++) {
			threads[i] = new Thread(new Runnable() {
				@Override
				public void run() {
					for (int i = 0; i < 1000000; i++) {
						increase();
					}
				}
			});
			threads[i].start();
		}
		// 等待所有累加线程都结束
		while (Thread.activeCount() > 1){
			Thread.yield();
		}
		long end = System.currentTimeMillis();
		System.out.println(end-start);
		System.out.println(race);

	}
}